import React, {
    useState,
    useEffect,
    useRef,
    useMemo,
    useCallback,
  } from "react";
import { Table, Button, Space, Tooltip, message } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http';
import { AadTokenProvider } from '@microsoft/sp-http';

const MeetingCalendar = (props) => {
  console.log('CalendarPlan props:', props);
  const [timeRange, setTimeRange] = useState('past-week');
  const [calendarData, setCalendarData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // 获取日历数据
  const fetchCalendarData = async () => {
    try {
      setLoading(true);
      
      // 计算时间范围
      const now = new Date();
      let startDate, endDate;
      
      switch(timeRange) {
        case 'past-week':
          startDate = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
          endDate = now;
          break;
        case 'next-two-weeks':
          startDate = now;
          endDate = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000);
          break;
        case 'next-four-weeks':
          startDate = now;
          endDate = new Date(now.getTime() + 28 * 24 * 60 * 60 * 1000);
          break;
        default:
          startDate = now;
          endDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
      }

      // 格式化日期为ISO字符串
      const startDateStr = startDate.toISOString();
      const endDateStr = endDate.toISOString();

      // Get current user email
      const currentUserEmail = props.context.pageContext.user.email;

      // 使用 Microsoft Graph API 获取日历数据
      const graphClient = await props.context.msGraphClientFactory.getClient();
      const response = await graphClient
        .api('/me/calendarView')
        .query({
          startDateTime: startDateStr,
          endDateTime: endDateStr,
          $select: 'subject,start,end,location,attendees,responseStatus'
        })
        .get();

      console.log("日历数据", response);

      // 转换数据格式
      const formattedData = response.value.map((event, index) => {
        // Find the current user's attendance status
        const currentUserAttendee = event.attendees?.find(attendee => 
          attendee.emailAddress.address === currentUserEmail
        );

        let statusText = '未确定'; // Default status
        let statusType = 'warning'; // Default type

        if ( currentUserAttendee) {
          switch (currentUserAttendee.status?.response) {
            case 'accepted':
              statusText = '确定参加';
              statusType = 'success';
              break;
            case 'tentativelyAccepted':
              statusText = '暂定参加';
              statusType = 'warning';
              break;
            case 'declined':
              statusText = '拒绝';
              statusType = 'error'; // Use 'error' for declined status for better styling
              break;
            case 'none':
              statusText = '未确定';
              statusType = 'warning';
              break;
            default:
              statusText = '未确定';
              statusType = 'warning';
          }

}
        return {
          key: index.toString(),
          id: index + 1,
          title: event.subject,
          startTime: new Date(event.start.dateTime).toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            weekday: 'short',
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'Asia/Shanghai'
          }),
          endTime: new Date(event.end.dateTime).toLocaleString('zh-CN', {
            month: 'numeric',
            day: 'numeric',
            weekday: 'short',
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'Asia/Shanghai'
          }),
          location: event.location?.displayName || '未指定',
          participants: event.attendees?.map(a => a.emailAddress.name).join('、') || '无参与者',
          status: {
            text: statusText,
            type: statusType // Use the determined status type
          }
        };
      });

      setCalendarData(formattedData);
    } catch (error) {
      console.error('Error fetching calendar data:', error);
      message.error('获取日历数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // Handle table pagination, sorting, and filtering changes
  const handleTableChange = (pagination, filters, sorter) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
    // Note: Sorting and filtering logic can be added here if needed in the future
  };

  // 监听时间范围变化
  useEffect(() => {
    if (props.context) {
      fetchCalendarData();
    }
  }, [timeRange, props.context]);

  // 获取会议数量
  const getMeetingCount = () => {
    return calendarData.length;
  };

  // 获取忙碌状态
  const getBusyStatus = () => {
    const count = getMeetingCount();
    if (count > 10) {
      return {
        status: '忙碌',
        emoji: '😢',
        description: '(会议数量超过10个，非常忙碌)'
      };
    } else if (count > 5) {
      return {
        status: '适中',
        emoji: '😐',
        description: '(会议数量在5-10个之间，适中)'
      };
    } else {
      return {
        status: '轻松',
        emoji: '😀',
        description: '(会议数量少于5个，比较轻松)'
      };
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '5%',
    },
    {
      title: '事件标题',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      ellipsis: {
        showTitle: false,
      },
      render: title => (
        <span>{title}</span>
      ),
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: '15%',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: '15%',
    },
    {
      title: '地点',
      dataIndex: 'location',
      key: 'location',
      width: '10%',
      ellipsis: {
        showTitle: false,
      },
      render: location => (
        <Tooltip placement="topLeft" title={location}>
          <span className="hover-content">{location}</span>
        </Tooltip>
      ),
    },
    {
      title: '参与者',
      dataIndex: 'participants',
      key: 'participants',
      width: '25%',
      ellipsis: {
        showTitle: false,
      },
      render: participants => (
        <Tooltip placement="topLeft" title={participants}>
          <span className="hover-content">{participants}</span>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '15%',
      render: (status) => (
        <span 
          className={`status-${status.type}`}
        >
          {status.text}
        </span>
      ),
    },
  ];

  // 设置行样式为偶数行浅蓝色背景
  const getRowClassName = (record, index) => {
    return index % 2 === 1 ? 'light-blue-row' : '';
  };

  const busyStatus = getBusyStatus();

  return (
    <div className="calendar-container">
      <div className="header-section">
        <h2 className="page-title">趣议周章</h2>
        <p className="meeting-info">
          {timeRange === 'past-week' ? '过去7天' : timeRange === 'next-two-weeks' ? '未来两周' : '未来四周'}你一共有 
          <span className="meeting-count"> {getMeetingCount()} </span> 个会议
        </p>
        <div className="status-section">
          <div className="status-icon-container">
            <span className="status-emoji">{busyStatus.emoji}</span>
          </div>
          <span className="status-text">{busyStatus.status}</span>
          <span className="status-description">{busyStatus.description}</span>
        </div>
        
        <div className="button-container">
          <Space>
            <Button 
              type={timeRange === 'past-week' ? 'primary' : 'default'} 
              ghost={timeRange === 'past-week'}
              onClick={() => setTimeRange('past-week')}
            >
              过去一周
            </Button>
            <Button 
              type={timeRange === 'next-two-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-two-weeks'}
              onClick={() => setTimeRange('next-two-weeks')}
            >
              未来两周
            </Button>
            <Button 
              type={timeRange === 'next-four-weeks' ? 'primary' : 'default'} 
              ghost={timeRange === 'next-four-weeks'}
              onClick={() => setTimeRange('next-four-weeks')}
            >
              未来四周
            </Button>
          </Space>
        </div>
      </div>
      
      <Table
        dataSource={calendarData}
        columns={columns}
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: calendarData.length,
          showSizeChanger: true,
          showQuickJumper: true,
          position: ['bottomRight'],
        }}
        onChange={handleTableChange}
        rowClassName={getRowClassName}
        className="table-container"
        scroll={{ x: true }}
        loading={loading}
      />

      <style jsx="true">
        {`
          .calendar-container {
            padding: 20px;
          }
          .light-blue-row {
            background-color: #f0f8ff;
          }
          .ant-table-tbody > tr.light-blue-row:hover > td {
            background-color: #e6f4ff;
          }
          .page-title {
            margin: 0 0 10px 0;
          }
          .meeting-info {
            margin: 10px 0;
          }
          .status-icon-container {
            background-color: #ffd591;
            padding: 4px;
            border-radius: 4px;
            margin-right: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .status-emoji {
            font-size: 20px;
          }
          .status-text {
            margin-right: 8px;
            font-weight: 500;
          }
          .status-description {
            color: #999;
          }
          .button-container {
            display: flex;
            justify-content: flex-end;
            margin-bottom: 15px;
          }
          .meeting-count {
            color: #1890ff;
            font-size: 18px;
            font-weight: bold;
          }
          .header-section {
            margin-bottom: 20px;
          }
          .status-section {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
          }
          .table-container {
            background-color: #fff;
            width: 100%;
          }
          .hover-content {
            cursor: pointer;
          }
          .status-success {
            color: #52c41a;
          }
          .status-warning {
            color: #fa8c16;
          }
          .status-error {
            color: #f5222d;
          }
          .ant-table-container {
            width: 100%;
          }
          .ant-table {
            width: 100%;
          }
          .ant-table-cell {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          .ant-table-wrapper {
            width: 100%;
          }
        `}
      </style>
    </div>
  );
};

export default MeetingCalendar;